package de.cbf.cam.dsa.model.persistence;

import java.lang.reflect.InvocationTargetException;
import java.util.Properties;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;

import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.jface.dialogs.ProgressMonitorDialog;
import org.eclipse.jface.operation.IRunnableWithProgress;
import org.eclipse.swt.widgets.Shell;

import de.cbf.cam.dsa.model.Activator;

/**
 * Class implementing the singleton pattern for the one and only EntityManagerFactory object. 
 */
public class HibernateUtil {
	
	private static EntityManagerFactory entityManagerFactory;
	
	/* (non-Javadoc)
	 * @see java.lang.Object#finalize()
	 */
	@Override
	protected void finalize() throws Throwable {
		entityManagerFactory.close();
		//
		super.finalize();
	}


	/**
	 * Provide new EntityManager from applications one and only entityManagerFactory object
	 * 
	 * @return new EntityManager object
	 */
	public static EntityManager getEntityManager(){ 
		if(entityManagerFactory == null){
			//specify runnable
			IRunnableWithProgress emCreator = new IRunnableWithProgress(){
				@Override
				public void run(IProgressMonitor monitor)
						throws InvocationTargetException, InterruptedException {

					monitor.beginTask("Initializing Database",IProgressMonitor.UNKNOWN);
					entityManagerFactory = Persistence.createEntityManagerFactory("de.cbf.cam.dsa", new Properties());
				};
			};
			//get shell for dialog
			Shell shell = Activator.getDefault().getWorkbench().getActiveWorkbenchWindow().getShell();
			//create and run dialog
			ProgressMonitorDialog dialog = new ProgressMonitorDialog(shell);			
			try {
				dialog.run(false, false, emCreator);
			} catch (InvocationTargetException e) {				
				Activator.logger.error("Error running EM Creation", e);
			} catch (InterruptedException e) {				
				Activator.logger.error("Error running EM Creation", e);
			}
			shell.pack();
			shell.open();
		}

		

		return entityManagerFactory.createEntityManager();
	}	
	
	
}